package com.lyh.commom.BizException;


import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/***
 * BizException 拦截处理
 * @author lyh
 */
@Component
class HandlerException extends ExceptionHandlerExceptionResolver {

    private static FastJsonConfig fastJsonConfig;

    static {

        fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
    }

    @Override
    public ModelAndView doResolveHandlerMethodException(HttpServletRequest request,

                                                        HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) {

        ModelAndView mv = new ModelAndView();
        BizException ex = null;
        if (exception instanceof BizException) {
            ex = (BizException) exception;
            Map map = new HashMap(5);
            map.put("errno", StringUtils.isEmpty(ex.getErrorCode()) ? "0000" : ex.getErrorCode());
            map.put("msg", ex.getMsg());
            map.put("success", false);
            map.put("data", null);
            FastJsonJsonView view = new FastJsonJsonView();
            //写出null值
            view.setFastJsonConfig(fastJsonConfig);
            view.setAttributesMap(map);
            mv.setView(view);
        }
        return mv;
    }
}
